<?php

namespace App\Http\Controllers\Admin\Finance;

use App\Http\Controllers\Controller;
use App\Http\Requests\finance\CompensationRequest;
use App\Models\examine\RecordModel;
use App\Models\FlightModel;
use App\Models\OrderModel;
use App\Models\finance\CompensationModel;
use App\Models\service\CompensateModel;
use App\Models\TakeOrderModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Compensation extends Controller
{
    use CompensationRequest;

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $take_order_sn = $request->input('take_order_sn', '');
        $status = $request->input('status', '');
        $create_start = $request->input('create_start', '');
        $create_end = $request->input('create_end', '');


        $query = CompensationModel::query()->with(['compensate_admin', 'actual_currency', 'currency', 'agent'])->withWhereHas('take_order', function ($query) use ($take_order_sn) {
            if($take_order_sn) {
                $query->where('sn', $take_order_sn);
            }
        });

        if($status){
            $query = $query->where('status', $status);
        }

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'agent_id' => $item->id,
                'agent_name' => $item->agent ? $item->agent->name : '',
                'take_order_sn' => $item->take_order ? $item->take_order->sn : '',
                'amount' => $item->amount,
                'currency_id' => $item->currency_id,
                'currency_symbol' => $item->currency ? $item->currency->symbol : '',
                'actual_amount' => $item->actual_amount,
                'actual_currency_symbol' => $item->actual_currency ? $item->actual_currency->symbol : '',
                'remarks' => $item->remarks,
                'compensate_remarks' => $item->compensate_remarks,
                'status' => $item->status,
                'status_text' => CompensationModel::STATUS[$item->status],
                'compensate_admin_user' => $item->compensate_admin ? $item->compensate_admin->name : '',
                'created_at' => $item->created_at->toDateTimeString(),
                'number' => $item->number,
                'weight' => $item->weight,
                'flight_date' => $item->flight_date,
                'start_port_code' => $item->start_port_code,
                'arrive_port_code' => $item->arrive_port_code,
                'carrier' => $item->carrier,
                'pod_file' => $item->pod_file,
                'letter_file' => $item->letter_file,
                'invoice_file' => $item->invoice_file,
                'list_file' => $item->list_file,
                'pic_file' => $item->pic_file ? json_decode($item->pic_file) : [],
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }


    /**
     * Notes:发起赔偿
     * User: xiangzi
     * Date: 2024/9/19
     * Time: 17:52
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request, $id){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = CompensateModel::find($id);
        if(!$model){
            return $this->error('数据不存在');
        }

//        $order = OrderModel::find($model->order_id);

        $take_order = TakeOrderModel::find($model->take_order_id);

        DB::beginTransaction();
        try {

            $compensate = new CompensationModel();
            $compensate->take_order_id = $take_order->id;
            $compensate->agent_id = $params['agent_id'];
            $compensate->carrier = $params['carrier'] ??  '';
            $compensate->amount = $params['amount'];
            $compensate->currency_id = $params['currency_id'];
            $compensate->pod_file = $params['pod_file'];
            $compensate->letter_file = $params['letter_file'];
            $compensate->invoice_file = $params['invoice_file'];
            $compensate->list_file = $params['list_file'];
            $compensate->remarks = $params['remarks'] ?? '';
            $compensate->pic_file = $params['pic_file'] ? json_encode($params['pic_file']) : '';

            $compensate->flight_date = $model->flight_date;
            $compensate->number = $model->number;
            $compensate->weight = $model->weight;
            $compensate->start_port_code = $model->start_port_code;
            $compensate->arrive_port_code = $model->arrive_port_code;

            $compensate->created_admin_id = $auth->id;

            $compensate->save();

            $model->is_record = 1;
            $model->save();

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    //发起赔偿
    public function admin_add(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::admin_add_check($params);

        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $take_order_sn = $params['take_order_sn'] ?? '';
        $take_order = TakeOrderModel::where('sn', $take_order_sn)->first();
        if(!$take_order){
            return $this->error('提单不存在');
        }

        $flight = FlightModel::where('id', $take_order->flight_id)->first();

        $flight_date = '';
        if($flight){
            if($flight->flight_date){
                $flight_date = $flight->flight_date;
            }else{
                $flight_date = date('Y-m-d', strtotime($flight->take_off_time));
            }
        }


        $compensate = new CompensationModel();
        $compensate->take_order_id = $take_order->id;
        $compensate->agent_id = $params['agent_id'];
        $compensate->carrier = $params['carrier'] ??  '';
        $compensate->amount = $params['amount'];
        $compensate->currency_id = $params['currency_id'];
        $compensate->pod_file = $params['pod_file'];
        $compensate->letter_file = $params['letter_file'];
        $compensate->invoice_file = $params['invoice_file'];
        $compensate->list_file = $params['list_file'];
        $compensate->remarks = $params['remarks'] ?? '';
        $compensate->pic_file = $params['pic_file'] ? json_encode($params['pic_file']) : '';

        $compensate->flight_date = $flight_date;
        $compensate->number = $params['number'] ?? 0;
        $compensate->weight = $params['weight'] ?? 0;
        $compensate->start_port_code = $flight ? $flight->start_port_code : '';
        $compensate->arrive_port_code = $flight ? $flight->arrive_port_code : '';

        $compensate->created_admin_id = $auth->id;

        $compensate->save();

        return $this->success();
    }

    /**
     * Notes:修改
     * User: xiangzi
     * Date: 2024/9/19
     * Time: 17:52
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id){
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = CompensationModel::find($id);
        if(!$model){
            return $this->error('数据不存在');
        }

        $model->agent_id = $params['agent_id'];
        $model->amount = $params['amount'];
        $model->currency_id = $params['currency_id'];
        $model->pod_file = $params['pod_file'];
        $model->letter_file = $params['letter_file'];
        $model->invoice_file = $params['invoice_file'];
        $model->list_file = $params['list_file'];
        $model->remarks = $params['remarks'] ?? '';
        $model->pic_file = json_encode($params['pic_file']);

        $model->save();


        return $this->success();
    }


    /**
     * Notes:确认赔偿
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function confirm(Request $request, $id){
        $params = $request->all();

        $model = CompensationModel::find($id);
        if(!$model){
            return $this->error('数据不存在');
        }

        $check_res = self::confirm_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model->actual_amount = $params['actual_amount'];
        $model->actual_currency_id = $params['actual_currency_id'];
        $model->status = 2;
        $model->compensate_remarks = $params['compensate_remarks'] ?? '';
        $model->compensate_time = date('Y-m-d H:i:s');
        $model->save();

        return $this->success();
    }



    /**
     * Notes:详情
     * User: xiangzi
     * Date: 2024/9/20
     * Time: 11:30
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request, $id){
        $model = CompensationModel::with(['compensate_admin', 'actual_currency', 'currency', 'agent', 'take_order'])->find($id);
        if(!$model){
            return $this->error('数据不存在');
        }


        $return = [
            'base_info' => [
                'agent_name' => $model->agent ? $model->agent->name : '',
                'take_order_sn' => $model->take_order ? $model->take_order->sn : '',
                'created_at' => $model->created_at->toDateTimeString(),
                'amount' => $model->amount,
                'currency_symbol' => $model->currency ? $model->currency->symbol : '',
                'remarks' => $model->remarks,
                'letter_file' => $model->letter_file,
                'pod_file' => $model->pod_file,
                'invoice_file' => $model->invoice_file,
                'list_file' => $model->list_file,
                'status' => $model->status,
                'status_text' => CompensationModel::STATUS[$model->status],
                'pic_file' => $model->pic_file ? json_decode($model->pic_file, true) : []
            ],
            'compensate_info' => [
                'actual_amount' => $model->actual_amount,
                'actual_currency_symbol' => $model->actual_currency ? $model->actual_currency->symbol : '',
                'compensate_remarks' => $model->compensate_remarks,
                'compensate_admin_user' => $model->compensate_admin ? $model->compensate_admin->name : '',
                'compensate_time' => $model->compensate_time,
            ]
        ];
        return $this->success($return);
    }


}
